package com.vidmt.api.modules.sys.web;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.vidmt.api.common.exceptions.BadParamException;
import com.vidmt.api.common.pojo.ApiResultServer;
import com.vidmt.api.common.utils.CommUtil;
import com.vidmt.api.common.utils.XmlD4jUtil;
import com.vidmt.api.common.web.ApiController;
import com.vidmt.api.modules.sys.Acc;
import com.vidmt.api.modules.sys.Enums.AccType;
import com.vidmt.api.modules.sys.entity.Location;
import com.vidmt.api.modules.sys.entity.Order;
import com.vidmt.api.modules.sys.entity.Role;
import com.vidmt.api.modules.sys.entity.User;
import com.vidmt.api.modules.sys.entity.sub.RoleLvl;
import com.vidmt.api.modules.sys.pay.wx.WxCerHttps;
import com.vidmt.api.modules.sys.pay.wx.WxPayConfig;
import com.vidmt.api.modules.sys.pay.wx.WxPayUtil;
import com.vidmt.api.modules.sys.service.LocationService;
import com.vidmt.api.modules.sys.service.OrderService;
import com.vidmt.api.modules.sys.service.RoleService;
import com.vidmt.api.modules.sys.service.UserService;

/**
 * 用户Controller
 * 
 * @author ThinkGem
 * @version 2013-8-29
 */
@Controller
@RequestMapping(value = "${adminPath}/web/user")
public class WebUserController extends ApiController {
	private static final Logger log = LoggerFactory.getLogger(WebUserController.class);
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private LocationService locationService;

	@RequestMapping(value = { "index.html" })
	public String index(Model model) {
		long cnt = userService.getUserCount();
		model.addAttribute("totaluser", cnt);
		return "modules/user/index";
	}

	@ResponseBody
	@RequestMapping(value = { "/list.*" })
	public ApiResultServer list(Long uid, String phone, String tradeno) {
		List<User> list = new ArrayList<>();
		Acc acc = null;
		if (uid != null) {
			acc = new Acc(AccType.uid, uid.toString());
		} else if (phone != null) {
			acc = new Acc(AccType.phone, phone);
		} else if (tradeno != null) {
			Order order = orderService.findByTradeno(tradeno);
			if (order != null) {
				acc = new Acc(AccType.uid, order.getUid() + "");
			}
		}
		if (acc != null) {
			User user = null;
			if (acc.type() == AccType.uid) {
				user = userService.load(Long.valueOf(acc.value()));
			} else {
				user = userService.findByAcc(acc);
			}
			if (user != null) {
				Map<Long, Boolean> map = userService.isOnline(user.getId());
				user.setOnline(map.get(user.getId()));
			}
			list.add(user);
		} else {
			list = userService.findAll();
		}
		if (!CommUtil.isEmpty(list)) {
			for (User user : list) {
				List<Order> orderlist = orderService.findByUid(user.getId());
				if (!CommUtil.isEmpty(list)) {
					user.setOrders(orderlist);
				}
				user.setLocation(locationService.findByUid(user.getId()));
			}
		}
		return new ApiResultServer(list);
	}

	@ResponseBody
	@RequestMapping(value = { "/delete.*" })
	public ApiResultServer delete(Long uid) {
		userService.deleteByUid(uid);
		return new ApiResultServer();
	}

	@ResponseBody
	@RequestMapping("/update.*")
	public ApiResultServer updateuser(User user) throws BadParamException {
		Long uid = user.getId();
		if (uid == null) {
			throw new BadParamException("uid不能为空");
		}
		if (user.getLvl() != null) {
			Role role = roleService.getRoleByKey(user.getLvl().name());
			RoleLvl lvl = new RoleLvl(role);
			userService.updateUserPayed(uid, lvl);
		} else {
			userService.updateUserExpired(user.getId());
		}
		return new ApiResultServer();
	}

	@ResponseBody
	@RequestMapping("/wxrefund.*")
	public ApiResultServer wxrefund(String tradeno) throws BadParamException {
		String refundUrl = "https://api.mch.weixin.qq.com/secapi/pay/refund";

		Order order = orderService.findByTradeno(tradeno);
		LinkedHashMap<String, String> params = new LinkedHashMap<>();
		String nonceStr = CommUtil.randString(32);
		params.put("appid", WxPayConfig.WXPAY_APP_ID);
		params.put("mch_id", WxPayConfig.WXPAY_MERCHANT_ID);
		params.put("nonce_str", nonceStr);
		params.put("op_user_id", WxPayConfig.WXPAY_MERCHANT_ID);
		params.put("out_refund_no", order.getId());
		params.put("refund_fee", order.getTotalFee() + "");
		params.put("total_fee", order.getTotalFee() + "");
		params.put("transaction_id", tradeno);
		String xml = WxPayUtil.toParamString(params);
		try {
			String resp = WxCerHttps.postStr(refundUrl, xml);
			Document doc = XmlD4jUtil.getXmlDoc(resp);
			Map<String, String> notifyMap = WxPayUtil.readXml(doc);
			if (!"SUCCESS".equals(notifyMap.get("return_code")) || !"SUCCESS".equals(notifyMap.get("result_code"))) {
				throw new IllegalStateException(JSON.toJSONString(notifyMap));
			}

			orderService.refund(order, resp);

			return new ApiResultServer();
		} catch (Throwable e) {
			log.error("微信退款失败", e);
			return new ApiResultServer(e);
		}
	}
}
